package StudyCode.summary.regularexpressionsmatch;

import java.util.regex.Pattern;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GetStringStartArrayExpression {
	public static void main(String[] argv) {
		String[] terms = new String[]{"1", "abc", "level", "java2s.com", "asdf 123"};
		System.out.println(getStartsWithAnyPattern(terms));
	}


	public static Pattern getStartsWithAnyPattern(String[] terms) {
		StringBuffer sb = new StringBuffer();
		sb.append("(?s)\\A");
		buildFindAnyPattern(terms, sb);
		sb.append(".*");
		return Pattern.compile(sb.toString());
	}


	private static void buildFindAnyPattern(String[] terms, StringBuffer sb) {
		sb.append("(?:");
		for (int i = 0; i < terms.length; i++) {
			if (i > 0)
				sb.append("|");
			sb.append("(?:");
			sb.append(escapeRegularExpressionLiteral(terms[i]));
			sb.append(")");
		}
		sb.append(")");
	}


	public static String escapeRegularExpressionLiteral(String s) {

		int length = s.length();
		int newLength = length;
		for (int i = 0; i < length; i++) {
			char c = s.charAt(i);
			if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) {
				newLength += 1;
			}
		}
		if (length == newLength) {
			return s;
		}
		StringBuffer sb = new StringBuffer(newLength);
		for (int i = 0; i < length; i++) {
			char c = s.charAt(i);
			if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) {
				sb.append('\\');
			}
			sb.append(c);
		}
		return sb.toString();
	}
}
